/*
 * Copyright (c) zhg2yqq.com Corp.
 * All Rights Reserved.
 */
package com.zhg2yqq.wheels.security.handler;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.web.session.InvalidSessionStrategy;

import com.alibaba.fastjson2.JSON;
import com.zhg2yqq.wheels.common.response.RestResponse;
import com.zhg2yqq.wheels.security.ISecurityEventHook;
import com.zhg2yqq.wheels.security.constants.SecurityResponseCode;

/**
 * @author zhg2yqq, 2022年11月28日
 * @version zhg2yqq v1.0
 */
public class InvalidSessionHandler implements InvalidSessionStrategy {
    private Logger log = LoggerFactory.getLogger(InvalidSessionHandler.class);
    private ISecurityEventHook eventHook;

    public InvalidSessionHandler() {
        super();
    }

    public InvalidSessionHandler(ISecurityEventHook eventHook) {
        super();
        this.eventHook = eventHook;
    }

    @Override
    public void onInvalidSessionDetected(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        log.info("用户登录超时，访问[{}]失败", request.getRequestURI());
        if (eventHook != null) {
//            eventHook.loginInvalidEvent(principal, request);
        }
        // 允许跨域
        response.setHeader("Access-Control-Allow-Origin", "*");
        // 允许自定义请求头token(允许head跨域)
        response.setHeader("Access-Control-Allow-Headers",
                "token, Accept, Origin, X-Requested-With, Content-Type, Last-Modified");
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(
                JSON.toJSONString(RestResponse.fail(SecurityResponseCode.SECURITY_IS_TIMEOUT)));
    }
}
